import Vue from 'vue'
const state = {
  stage: {
    id: '',
    name: ''
  }
}

const getters = {
  getStage: state => {
    return state.stage
  }
}

const mutations = {
  muStage (state, payload) {
    state.stage = payload
  },
  editStage (state, payload) {
    state.stage = {...state.stage, ...payload}
  }
}

const actions = {
  actStage ({ commit }, payload) {
    return new Promise((resolve, reject) => {
      let obj = Vue.prototype.$getParameterMap()
      if (obj && obj.stageId && obj.dateTime) {
        let currentCookie = JSON.parse(Vue.prototype.$getCookie('currentUser'))
        Vue.prototype.$setCookie('currentUser', JSON.stringify(currentCookie), {stageId: obj.stageId, dateTime: obj.dateTime, domain: Vue.prototype.$site.domain})
        // 成功回调
        Vue.prototype.$store.commit('editCurrentUser', {stageId: obj.stageId, dateTime: obj.dateTime})
        resolve()
      } else {
        const data = {
          projectId: Vue.prototype.$store.getters.currentUser.pjId
        }
        Vue.prototype.$axios({
          method: 'post',
          url: `${Vue.prototype.$site.videoServer}/api/screen/getCurrentStageList`,
          data: Vue.prototype.$qs.stringify(data)
        }).then(res => {
          if (res.data.errorMsg) {
            reject(res.data.errorMsg)
          } else {
            if (res.data.data.length === 0) {
              reject('该项目下没有分期')
            } else {
              let currentCookie = JSON.parse(Vue.prototype.$getCookie('currentUser'))
              Vue.prototype.$setCookie('currentUser', JSON.stringify(currentCookie), {stageId: res.data.data[0].stageId, domain: Vue.prototype.$site.domain})
              // 成功回调
              Vue.prototype.$store.commit('editCurrentUser', {stageId: res.data.data[0].stageId})
              let stageID = res.data.data[0].stageId
              Vue.prototype.$axios({
                method: 'post',
                url: `${Vue.prototype.$site.videoServer}/api/panorama/getPanoramaUpdateTime`,
                data: Vue.prototype.$qs.stringify({stageId: stageID})
              }).then(res => {
                if (!res.data.data) reject(res.data.errorMsg)
                let upDateTime = res.data.data
                let currentCookie = JSON.parse(Vue.prototype.$getCookie('currentUser'))
                Vue.prototype.$setCookie('currentUser', JSON.stringify(currentCookie), {dateTime: upDateTime[0], domain: Vue.prototype.$site.domain})
                // 成功回调
                Vue.prototype.$store.commit('editCurrentUser', {dateTime: upDateTime[0]})
                resolve(res)
              })
            }
          }
        }, () => {
          reject('获取分期出错')
        })
      }
    })
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
